package main

import (
	"database/sql"
	"fmt"
	"github.com/gin-gonic/gin"
	_ "github.com/go-sql-driver/mysql"
	"net/http"
)

const (
	mysql_user   = "root"
	mysql_passwd = "123456"
	mysql_ip     = "127.0.0.1"
	mysql_port   = "3306"
	mysql_qyDB   = "go_test"
)

// album 表示有关专辑的数据.
type album struct {
	ID     string  `json:"id"`
	Title  string  `json:"title"`
	Artist string  `json:"artist"`
	Price  float64 `json:"price"`
}

type user struct {
	Id       string `json:"id"`
	Name     string `json:"name"`
	Password string `json:"password"`
}

// 专辑切片以填充专辑数据记录.
var albums = []album{
	{ID: "1", Title: "Blue Train", Artist: "John Coltrane", Price: 56.99},
	{ID: "2", Title: "Jeru", Artist: "Gerry Mulligan", Price: 17.99},
	{ID: "3", Title: "Sarah Vaughan and Clifford Brown", Artist: "Sarah Vaughan", Price: 39.99},
}

// getAlbums 以 JSON 格式响应所有专辑的列表.
func getAlbums(c *gin.Context) {
	c.IndentedJSON(http.StatusOK, albums)
}

func getUser(c *gin.Context) {
	id := c.Query("id")
	//value := c.PostForm("somePostParam")
	name, password := funReadSql(id)
	result := user{Name: name, Password: password}
	c.IndentedJSON(http.StatusOK, result)
}

func main() {
	router := gin.Default()
	router.GET("/albums", getAlbums)
	router.GET("/user", getUser)

	router.Run(":8080")
}

func funReadSql(id string) (string, string) {
	//打开数据库
	db, errOpen := sql.Open("mysql", mysql_user+":"+mysql_passwd+"@tcp("+mysql_ip+":"+mysql_port+")/"+mysql_qyDB+"?charset=utf8")
	if errOpen != nil {
		//TODO，这里只是打印了一下，并没有做异常处理
		fmt.Println("funReadSql Open is error")
	}

	//读取t_knowledge_tree表中codeName和answer字段
	var name, password string
	errTables := db.QueryRow("SELECT name,password FROM user WHERE id=?", id).Scan(&name, &password)
	if errTables != nil {
		//TODO，这里只是打印了一下，并没有做异常处理
		fmt.Println("funReadSql SELECT t_knowledge_tree is error", errTables)
	}

	//关闭数据库
	db.Close()
	return name, password
}

